package cn.org.spring.wechar.controller;

import cn.org.spring.common.util.HttpClientUtils;
import cn.org.spring.wechar.config.WeCharConfig;
import cn.org.spring.wechar.constant.WeCharConstant;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User:  wanghongjie
 * Date:  2020/11/1 - 09:07
 * <p>
 * Description:
 */
@Slf4j
@RestController
@RequestMapping("/v1/weChar")
public class UserInfoController {

    @Autowired
    private WeCharConfig charConfig;

    /**
     * 回调链接
     * 1、获取code -> 获取accessToken ->获取用户基本信息
     */
    @RequestMapping("/getCode")
    public String getCode(@RequestParam("code") String code) throws IOException {
        System.out.println(code);
        String userInfo = getAccessToken(code);
        log.info("获取用户的基本信息 【{}】", userInfo);
        return userInfo;
    }

    /**
     * 获取accessToken 和 openID
     *
     * @param code
     * @return
     * @throws IOException
     */
    public String getAccessToken(String code) throws IOException {
        String s = HttpClientUtils.get(WeCharConstant.OAUTH_GET_AT.replace("APPID", charConfig.getAppId())
                .replace("SECRET", charConfig.getSecret()).replace("CODE", code));
        System.out.println("获取access token " + s);
        String access_token = JSON.parseObject(s).getString("access_token");
        String openid = JSON.parseObject(s).getString("openid");
        return getUserInfo(access_token, openid);
    }

    /**
     * 获取用户基本信息
     *
     * @param accessToken
     * @param openId
     * @return
     * @throws IOException
     */
    public String getUserInfo(String accessToken, String openId) throws IOException {
        return HttpClientUtils.get(WeCharConstant.OAUTH_USER_INFO.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId));
    }
}